package itsm.isperp.framework.data.mybatis.type;

import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

/**
 * 
 * 
 * 
 * @author lizx
 * @date 2014-11-22
 * @since 1.0
 * 
 */
public class OracleBlobTypeHandler extends BaseTypeHandler<String> {

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i,
			String parameter, JdbcType jdbcType) throws SQLException {

		byte[] bs;
		try {
			bs = parameter.getBytes("UTF-8");

			ByteArrayInputStream bis = new ByteArrayInputStream(bs);
			ps.setBinaryStream(i, bis, bs.length);
		} catch (UnsupportedEncodingException e) {
			ps.setBinaryStream(i, null);
		}
	}

	@Override
	public String getNullableResult(ResultSet rs, String columnName)
			throws SQLException {
		Blob blob = rs.getBlob(columnName);
		byte[] returnValue = null;
		if (null != blob) {
			returnValue = blob.getBytes(1, (int) blob.length());
		}
		try {
			return new String(returnValue, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			return null;
		}
	}

	@Override
	public String getNullableResult(ResultSet rs, int columnIndex)
			throws SQLException {
		Blob blob = rs.getBlob(columnIndex);
		byte[] returnValue = null;
		if (null != blob) {
			returnValue = blob.getBytes(1, (int) blob.length());
		}
		try {
			return new String(returnValue, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			return null;
		}

	}

	@Override
	public String getNullableResult(CallableStatement cs, int columnIndex)
			throws SQLException {
		Blob blob = cs.getBlob(columnIndex);
		byte[] returnValue = null;
		if (null != blob) {
			returnValue = blob.getBytes(1, (int) blob.length());
		}
		try {
			return new String(returnValue, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			return null;
		}
	}
}
